var express = require('express');
var session = require('express-session');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";


/* GET home page. */
router.get('/', function(req, res, next) {
    var logined='';
    if(req.session.userName != undefined){
        logined = "已经登录";
        res.redirect('/html/userPage.html');
    }else{
        logined = "没有登录";
        res.redirect('/html/login.html');
    }
});

router.post('/login', function(req, res, next) {
   console.log(req.body);
   var name = req.body.username;
   var pwd = req.body.pwd;

    var whereStr = {"name":name,"password":pwd};
    MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
        if (err) throw err;
        var dbo = db.db("zhihuishequ");
        dbo.collection("users"). find(whereStr).toArray(function(err, result) { // 返回集合中所有数据
            if (err) throw err;
            console.log(result);

            if(result.length){
                req.session.userName = name;
                res.redirect('/html/userPage.html');
            }else{
                res.send("登录错误，请检查用户名和密码");
            }
            db.close();
        });
    });
});

router.post('/logout', function(req, res, next) {
    var name =  req.session.userName;
    req.session.userName = null;
    res.send("you logout :" + name);
});

module.exports = router;
